package com.zmn.oms.admin.controller.conf.attachment;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.common.query.area.AreaQuery;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.base.plat.engine.common.util.response.DubboResponseUtils;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.AMISListData;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.conf.attachment.ConfOrderAttachmentBService;
import com.zmn.oms.business.interfaces.conf.attachment.ConfOrderAttachmentStandardBService;
import com.zmn.oms.common.constant.OrderAttachmentCategoryTypeEnum;
import com.zmn.oms.common.dto.ActivityCityGroupDTO;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.dto.TreeGridDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dio.conf.attachment.ConfOrderAttachmentDIO;
import com.zmn.oms.model.dto.conf.attachment.ConfOrderAttachmentStandardDTO;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachment;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachmentQuery;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachmentStandard;
import com.zmn.oms.model.entity.conf.attachment.channel.ConfOrderAttachmentChannelDRO;
import com.zmn.oms.model.entity.conf.attachment.city.ConfOrderAttachmentCityDRO;
import com.zmn.oms.model.vo.conf.attachment.ConfOrderAttachmentPictureVO;
import com.zmn.oms.model.vo.conf.attachment.ConfOrderAttachmentVO;
import com.zmn.oms.model.vo.conf.attachment.ConfOrderChannelQuery;
import com.zmn.oms.model.vo.conf.attachment.ServerClassDataBO;
import com.zmn.oms.services.interfaces.conf.attachment.ConfOrderAttachmentChannelService;
import com.zmn.oms.services.interfaces.conf.attachment.ConfOrderAttachmentProductService;
import com.zmn.oms.services.interfaces.conf.attachment.ConfOrderAttachmentService;
import com.zmn.oms.services.interfaces.conf.attachment.ConfOrderAttachmentStandardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 类描述：照片配置
 *
 * @author ligang
 * @date 2021/09/25 11:03
 */
@Controller
@RequestMapping("/conf/attachment/orderPicture")
@Slf4j
public class ConfOrderPictureController extends ConfOrderAttachmentController {

	@Resource
	private ConfOrderAttachmentStandardService confOrderAttachmentStandardService;
	@Resource
	private ConfOrderAttachmentStandardBService confOrderAttachmentStandardBService;
	@Resource
    private ConfOrderAttachmentBService confOrderAttachmentBService;

    @Resource
    private ConfOrderAttachmentChannelService confOrderAttachmentChannelService;

    @Resource
    protected ConfOrderAttachmentService confOrderAttachmentService;

    @Resource
    private ConfOrderAttachmentProductService confOrderAttachmentProductService;

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false, timeout = 10000)
    private ChannelListRemoteService channelListRemoteService;

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false, timeout = 10000)
    private ProductForeignListRemoteService productForeignListRemoteService;

    @RequestMapping(value = "/list")
    public ModelAndView list(ModelAndView mv) {
        mv.setViewName("conf/attachment/orderPicture/list");
        return mv;
    }

    /**
     * 查询列表 ajax
     */
    @RequestMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(ConfOrderAttachmentQuery query) {
        query.setType(OrderAttachmentCategoryTypeEnum.PICTURE.getCode());
        if (StringUtil.isNotBlank(query.getCategIds())) {
            query.setCategIdList(Lists.newArrayList(query.getCategIds().split(",")));
        }
        List<ConfOrderAttachmentVO> confList = confOrderAttachmentBService.listPicturePageByQuery(query);
        LayuiTableDO<ConfOrderAttachmentVO> data = new LayuiTableDO();
        data.setCount(query.getTotalCount());
        data.setData(confList);
        return ResultDTO.success(data);
    }

    /**
     * 查看/编辑
     *
     * @param mv
     * @param id
     * @return
     */
    @RequestMapping(value = "/addEdit")
    public ModelAndView detail(ModelAndView mv, Integer id) {
        List<ConfOrderAttachmentChannelDRO> confOrderAttachmentChannelDROS = new ArrayList();
        ConfOrderAttachment confOrderAttachment = new ConfOrderAttachment();
        List<ConfOrderAttachmentCityDRO> selectedCities = new ArrayList<>();
        List<Integer> servCategIds = new ArrayList<>();
        List<Integer> categOneIds = new ArrayList<>();
        List<Integer> categIds = new ArrayList<>();
        List<Integer> productIds = new ArrayList<>();
        if (Objects.nonNull(id)){
            // 这次是修改
            ConfOrderAttachmentPictureVO detail = confOrderAttachmentBService.getAttachmentConfigPictureDetail(id);
            confOrderAttachment = detail.getConfOrderAttachment();
            confOrderAttachmentChannelDROS = detail.getConfOrderAttachmentChannelDROS();
            selectedCities = detail.getSelectedCities();
            servCategIds = detail.getServCategIds();
            categOneIds = detail.getCategOneIds();
            categIds = detail.getCategIds();
            productIds = detail.getProductIds();
        }
        if (Objects.isNull(confOrderAttachment.getRephotograph())){
            confOrderAttachment.setRephotograph(true);
        }
        if (Objects.isNull(confOrderAttachment.getOrderDetailShow())){
            confOrderAttachment.setOrderDetailShow(true);
        }
        mv.setViewName("conf/attachment/orderPicture/newDetail");
        mv.addObject("dto", confOrderAttachment);
        final List<ActivityCityGroupDTO> activityCityGroupDTOS = city2group();
        mv.addObject("actCityGroupSet", activityCityGroupDTOS);
        mv.addObject("listChannel", confOrderAttachmentChannelDROS);
        mv.addObject("listCity", selectedCities);
        Map<Integer, Long> proviceSelectedCitiesNumber = new HashMap<Integer, Long>();
        if (CollectionUtil.isNotNullOrEmpty(selectedCities)) {
            proviceSelectedCitiesNumber = selectedCities.stream().filter(o -> Objects.nonNull(o.getProvinceId())).collect(Collectors.groupingBy(ConfOrderAttachmentCityDRO::getProvinceId, Collectors.counting()));
        }
        mv.addObject("proviceSelectedCitiesNumber", proviceSelectedCitiesNumber);
        final List<AreaDRO> allCityResponseDTO = DubboResponseUtils.resultToEmptyList(() -> areaListRemoteService.listAllCity());
        Map<Integer, Long> proviceAllCitiesNumber = allCityResponseDTO.stream().collect(Collectors.groupingBy(AreaDRO::getParentId, Collectors.counting()));
        mv.addObject("proviceAllCitiesNumber", proviceAllCitiesNumber);
        if (Objects.nonNull(confOrderAttachment) && Objects.nonNull(confOrderAttachment.getAllCity()) && confOrderAttachment.getAllCity()) {
            mv.addObject("limitCity", true);
        } else {
            final boolean limitCity = (CollectionUtil.isNotNullOrEmpty(selectedCities) && CollectionUtil.isNotNullOrEmpty(allCityResponseDTO)) && selectedCities.size() == allCityResponseDTO.size();
            mv.addObject("limitCity", limitCity);
        }
        mv.addObject("servCategIds", servCategIds);
        mv.addObject("categOneIds", categOneIds);
        mv.addObject("categIds", categIds);
        mv.addObject("productIds", productIds);
        return mv;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public ResultDTO delete(Integer id) {
        try {
            confOrderAttachmentBService.deleteByAttachmentId(id);
            return ResultDTO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public ResultDTO save(@RequestBody ConfOrderAttachmentDIO dio) {
        String msg = "";
        try {
            if (Objects.isNull(dio.getId())){
                msg = "新增照片配置成功";
                dio.setCreater(super.getCurrentStaff().getRealName());
                confOrderAttachmentBService.addConfPicture(dio);
            }else{
                msg = "修改照片配置成功";
                dio.setUpdater(super.getCurrentStaff().getRealName());
                confOrderAttachmentBService.modifyConfPictureById(dio);
            }
        }catch (OmsBaseException e){
            log.error("照片配置失败:{}",e.getMessage());
            return ResultDTO.fail(e.getMessage());
        }
        return ResultDTO.success(StatusConsts.STATUS_SUCCESS,msg);
    }

    /**
     * 加载产品数据
     * @param response 响应信息
     */
    @RequestMapping("/loadServerClassData")
    public void loadServerClassData(HttpServletResponse response) {
        Collection<ServerClassDataBO> promServerClassDROS = confOrderAttachmentBService.listAllServerClass();
        TreeGridDTO treeGrid = new TreeGridDTO<>();
        if (CollectionUtils.isNotEmpty(promServerClassDROS)) {
            treeGrid.setData(promServerClassDROS);
            treeGrid.setCount(promServerClassDROS.size());
        } else {
            treeGrid.setData(null);
            treeGrid.setCount(0);
        }
        ResponseUtil.outWriteJson(response, JSON.toJSONString(treeGrid));
    }

    /**
     * 查询渠道信息
     * @param query 渠道查询对象
     * @return mv
     */
    @RequestMapping("/listChannel")
    public ModelAndView listChannel(@ModelAttribute ConfOrderChannelQuery query) {
        ModelAndView modelAndView = new ModelAndView("conf/attachment/cooperation/list");
        ResponseDTO<AMISListData<ChannelDRO>> responseDTO = confOrderAttachmentBService.listChannel(query);
        List<ChannelDRO> list = new ArrayList<>();
        if (responseDTO.isSuccess()) {
            AMISListData data = responseDTO.getData();
            list = data.getItems();
            query.setTotalCount(data.getTotal());
        }
        modelAndView.addObject("items", list);
        modelAndView.addObject("vo", query);
        return modelAndView;
    }

    /**
     * 改是否审核
     */
    @RequestMapping(value = "/modifyNeedReview")
    @ResponseBody
    public ResultDTO modifyReview(ConfOrderAttachment conf) {
        logger.info("confCheckout[{}]", conf);
        conf.setUpdater(super.getCurrentStaff().getRealName());
        confOrderAttachmentBService.modifyConfReviewById(conf);
        return ResultDTO.success();
    }


    /**
     * 改是否必传
     */
    @RequestMapping(value = "/modifyMustUpload")
    @ResponseBody
    public ResultDTO modifyMustUpload(ConfOrderAttachment conf) {
        logger.info("confCheckout[{}]", conf);
        conf.setUpdater(super.getCurrentStaff().getRealName());
        confOrderAttachmentBService.modifyConfMustUploadById(conf);
        return ResultDTO.success();
    }

    /**
     * 改是否自动审核
     */
    @RequestMapping(value = "/modifyAutoAudit")
    @ResponseBody
    public ResultDTO modifyAutoAudit(ConfOrderAttachment conf) {
        conf.setUpdater(super.getCurrentStaff().getRealName());
        confOrderAttachmentBService.modifyConfAutoAuditById(conf);
        return ResultDTO.success();
    }

    /**
     * 改sort
     */
    @RequestMapping(value = "/modifySort")
    @ResponseBody
    public ResultDTO modifySort(ConfOrderAttachment conf) {
        log.info("confCheckout[{}]", conf);
        conf.setUpdater(super.getCurrentStaff().getRealName());
        confOrderAttachmentBService.modifyConfSortById(conf);
        return ResultDTO.success();
    }

    /**
     * 示例照片上传
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploader")
    @ResponseBody
    public ResultDTO uploaderImage(MultipartFile file) {
        return super.uploaderImage(file, "/oms/orderAttachment/photo");
    }

	/**
	 * 查询审核标准
	 *
	 * @param confAttachmentId
	 * @author liudi
	 * @since 2022-1-24 16:43:35
	 */
	@RequestMapping("/auditStandard")
	public ModelAndView auditStandard(ModelAndView mv, @RequestParam("id") Integer confAttachmentId) {
		ConfOrderAttachmentQuery query = ConfOrderAttachmentQuery.builder().id(confAttachmentId).build();
		ConfOrderAttachmentStandard standard = ConfOrderAttachmentStandard.builder().confAttachmentId(confAttachmentId).build();

		ConfOrderAttachmentVO confOrderAttachmentVO = confOrderAttachmentBService.listPageByQuery(query).get(0);
		ConfOrderAttachmentStandardDTO standardDTO = confOrderAttachmentStandardBService.listByQuery(standard);

		mv.setViewName("conf/attachment/orderPicture/auditStandard");
		mv.addObject("conf", confOrderAttachmentVO);
		mv.addObject("standardList", standardDTO.getAuditStandardList());
		return mv;
	}

	/**
	 * 新增/修改 照片审核标准
	 *
	 * @param dto
	 * @author liudi
	 * @since 2022-1-24 16:43:35
	 */
	@RequestMapping(value = "save/auditDetection")
	@ResponseBody
	public ResponseDTO auditDetection(@RequestBody ConfOrderAttachmentStandardDTO dto) {
		Date now = DateUtil.getNow();
		Integer confAttachmentId = dto.getConfAttachmentId();
		String operator = super.getCurrentStaff().getRealName();
		try {
			// 更新 附件配置表信息（是否配置了审核标准）
			boolean hasAuditStandardList = CollectionUtil.isNullOrEmpty(dto.getAuditStandardList());
			Integer flag = hasAuditStandardList ? GlobalConsts.NO : GlobalConsts.YES;
			ConfOrderAttachment confOrderAttachment = new ConfOrderAttachment();
			confOrderAttachment.setId(confAttachmentId);
			confOrderAttachment.setAutoAudit(flag);
			confOrderAttachment.setAuditStandardStatus(flag);
			confOrderAttachment.setUpdater(operator);
			confOrderAttachment.setUpdateTime(now);
			confOrderAttachmentService.updateConfById(confOrderAttachment);

			if (!hasAuditStandardList) {

				// 更新标准信息（先删除，后添加）
				confOrderAttachmentStandardService.deleteByAttachmentId(confAttachmentId);

				// 组装审核标准
				dto.getAuditStandardList().forEach(auditStandard -> {
                    ConfOrderAttachmentStandard newStandard = ConfOrderAttachmentStandard
                            .builder()
                            .confAttachmentId(confAttachmentId)
                            .auditStandard(JSON.toJSONString(auditStandard))
                            .creater(operator)
                            .createTime(now)
                            .updater(operator)
                            .updateTime(now)
                            .build();

                    // 新增操作
                    confOrderAttachmentStandardService.insertSelective(newStandard);
                });

            }
            return ResponseDTO.success(true, "操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("【新增/修改】工单照片审核标准失败，异常：{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    public List<ActivityCityGroupDTO> city2group() {
        // 所有城市
        AreaQuery query = new AreaQuery();
        query.setLevel(GlobalDict.AREA_LEVEL_CITY);
        query.setType(1);
        ResponseDTO<List<AreaDRO>> listResponseDTO = areaListRemoteService.listAllCity();

        List<AreaDRO> allCitiesDRO = listResponseDTO.getData();
        if (!listResponseDTO.isSuccess() || org.springframework.util.CollectionUtils.isEmpty(allCitiesDRO)) {
            return null;
        }
        List<AreaDRO> allCities = allCitiesDRO.stream().map(o -> {
            AreaDRO baseArea = new AreaDRO();
            BeanMapper.copy(o, baseArea);
            return baseArea;
        }).collect(Collectors.toList());
        // 所有省份下面的城市
        query.setLevel(GlobalDict.AREA_LEVEL_PROVINCE);
        ResponseDTO<List<AreaDRO>> proviceListResponseDTO = areaListRemoteService.listAreaByParentId(com.zmn.common.constant.GlobalConsts.TOP_ID);
        if (!proviceListResponseDTO.isSuccess() || org.springframework.util.CollectionUtils.isEmpty(proviceListResponseDTO.getData())) {
            return null;
        }
        List<AreaDRO> allProvincesDRO = proviceListResponseDTO.getData();
        List<AreaDRO> allProvinces = allProvincesDRO.stream().map(t -> {
            AreaDRO baseArea = new AreaDRO();
            BeanMapper.copy(t, baseArea);
            return baseArea;
        }).collect(Collectors.toList());

        final Map<Integer, Set<AreaDRO>> allCityMap = allCities.parallelStream()
                .collect(
                        Collectors.groupingBy(
                                AreaDRO::getParentId,
                                Collectors.mapping(it -> it, Collectors.toSet())
                        )
                );

        List<ActivityCityGroupDTO> actCityGroupLsit = new ArrayList<>();
        for (AreaDRO province : allProvinces) {
            if (!allCityMap.containsKey(province.getAreaId())) {
                continue;
            }
            ActivityCityGroupDTO activityCityGroupVo = new ActivityCityGroupDTO(province, allCityMap.get(province.getAreaId()));
            actCityGroupLsit.add(activityCityGroupVo);
        }

        return actCityGroupLsit;
    }



}
